/*
 * @author Chris
 * @since 2023/1/28 19:58
 *
 * @brief    The project will ...
 *
 * @note     ...
 *
 * @warning  Do not to ...
 *
 * Change Logs:
 *   Date           Author       Notes
 *   2023/1/28     Chris        the first version
 */
#include "reg51.h"

extern void InitLcd1602();

extern void Lcd1602ShowStr(unsigned char x, unsigned char y, unsigned char *buf, unsigned char len);

extern void I2CStart();

extern void I2CStop();

extern __sbit I2CWrite(unsigned char dat);

extern unsigned char I2CReadAck();

extern unsigned char I2CReadNack();

unsigned char E2ReadByte(unsigned char addr);

__sbit E2WriteByte(unsigned char addr, unsigned char dat);

int main() {
    InitLcd1602();

    unsigned char dat = E2ReadByte(0x02);
    unsigned char str[5];
    str[0] = (dat / 100) + '0';
    str[1] = (dat / 10 % 10) + '0';
    str[2] = (dat % 10) + '0';
    Lcd1602ShowStr(0, 0, str, 3);
    dat++;
    __sbit ack = E2WriteByte(0x02, dat);

    str[0] = 'a';
    str[1] = 'c';
    str[2] = 'k';
    str[3] = ':';
    str[4] = ack + '0';
    Lcd1602ShowStr(0, 1, str , 5);

    while (1);
}

__sbit E2WriteByte(unsigned char addr, unsigned char dat) {
    I2CStart();
    I2CWrite(0x50 << 1);
    I2CWrite(addr);
    __sbit ack = I2CWrite(dat);
    I2CStop();
    return ack;
}

unsigned char E2ReadByte(unsigned char addr) {
    I2CStart();
    I2CWrite(0x50 << 1);
    I2CWrite(addr);
    I2CStart();
    I2CWrite((0x50 << 1) | 0x01);   // 读
    unsigned char dat = I2CReadNack();
    I2CStop();

    return dat;
}

